<template>
  <l-layout :top="149" :topMove="false">
    <template #top>
      <div class="erpCase">
        <!-- 客户信息 -->
        <div class="form_div_back">
          <div class="panel_name_size_18">
            {{ $t(formData.case_erp_customer_f_Name) }}
          </div>

          <div class="form_information panel_margin_top_25">
            <div>{{ $t("客户类型:" + formData.case_erp_customer_f_Type) }}</div>
            <div class="panel_margin_left_50">
              {{ $t("所在行业:" + formData.case_erp_customer_f_Industry) }}
            </div>
            <div class="panel_margin_left_50">
              {{ $t("来源:" + formData.case_erp_customer_f_Source) }}
            </div>
            <div class="panel_margin_left_50">
              {{ $t("规模:" + formData.case_erp_customer_f_Scale) }}
            </div>
            <div class="panel_margin_left_50">
              {{ $t("公司性质:" + formData.case_erp_customer_f_ComNature) }}
            </div>
            <div class="panel_margin_left_50">
              {{ $t("地址:" + formData.case_erp_customer_f_Address) }}
            </div>
            <div class="panel_margin_left_50">
              {{ $t("归属:" + formData.case_erp_customer_f_ModifyUserName) }}
            </div>
          </div>
        </div>
      </div>
    </template>

    <div class="l-auto-window h48" style="padding: 0 16px">
      <el-button
        size="mini"
        class="addBtn"
        type="primary"
        style="margin-bottom: 16px"
        v-show="activeName == 'tab2'"
        @click.native="addContact"
      >
        {{ $t("新增联系人") }}</el-button
      >
      <el-button
        size="mini"
        class="addBtn"
        type="primary"
        style="margin-bottom: 16px"
        v-show="activeName == 'tab0'"
        @click.native="addFollowUp"
      >
        {{ $t("新增跟进") }}</el-button
      >
      <el-tabs v-model="activeName">
        <el-tab-pane
          class="l-tabs-container"
          :label="$t('跟进记录')"
          name="tab0"
        >
          <l-table
            ref="mainTable"
            :loading="followTableLoading"
            :key="Math.random()"
            :columns="case_erp_customerfollow_columns"
            :dataSource="case_erp_customerfollow_data"
            :isPage="true"
            :pageTotal="followTableTotal"
            :tablePage.sync="followTableCurrentPage"
          >
            <l-table-btns
              :filterBtns="filterBtns"
              :isAuth="false"
              :btns="followTableBtns"
              @click="lr_handleTableBtnClick"
            />
          </l-table>
        </el-tab-pane>
        <el-tab-pane
          class="l-tabs-container"
          :label="$t('客户信息')"
          name="tab1"
        >
          <div class="l-rblock">
            <div class="form_name form_top_upload">{{ $t("客户信息") }}</div>
            <div class="form_back form_top_upload lookImg form_information">
              <div>{{ $t("图片资料：") }}</div>
              <l-upload
                maxSize="2"
                sizeType="MB"
                :limit="9"
                :disabled="!isReadOnly"
                v-model="formData.case_erp_customer_f_File"
                listType="picture-card"
                :placeholder="$t('请输入')"
              />
            </div>
            <div class="form_back form_information form_top_upload">
              <div>
                {{ $t("创建日期：" + formData.case_erp_customer_f_CreateDate) }}
              </div>
              <div class="panel_margin_left_50">
                {{ $t("创建人" + formData.case_erp_customer_f_CreateUserName) }}
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane class="l-tabs-container" :label="$t('联系人')" name="tab2">
          <l-table
            ref="case_erp_customercontacts_table"
            :dataSource="case_erp_customercontacts_data"
            :columns="case_erp_customercontacts_columns"
          >
            <l-table-btns
              :btns="contactBtn"
              @click="lr_handleTableBtnClick"
            ></l-table-btns>
          </l-table>
        </el-tab-pane>
        <el-tab-pane
          class="l-tabs-container record_table"
          :label="$t('操作记录')"
          name="tab3"
        >
          <operationRecords :materialId="formData.case_erp_customer_f_Id" />
        </el-tab-pane>
      </el-tabs>

      <l-dialog
        :title="$t(formTitle)"
        :visible.sync="formVisible"
        :height="600"
        :width="800"
        @opened="handleOpenedForm"
        @ok="handleSave"
        @close="handleCloseForm"
      >
        <my-form
          v-if="this.formTitle == '新增联系人'"
          ref="form"
          :setBlock="false"
        ></my-form>
        <div v-else-if="this.formTitle == '联系人编辑'" style="padding: 8px">
          <el-form size="mini" labelPosition="right" labelWidth="80px">
            <el-row :gutter="16">
              <el-col :span="24">
                <el-form-item :label="$t('姓名')" labelWidth="60px">
                  <el-input
                    v-model="
                      contactList.caseErpCustomercontactsList[contactIndex]
                        .f_Name
                    "
                    :placeholder="$t('请输入')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('电话')" labelWidth="60px">
                  <el-input
                    v-model="
                      contactList.caseErpCustomercontactsList[contactIndex]
                        .f_Phone
                    "
                    :placeholder="$t('请输入')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('职业')" labelWidth="60px">
                  <el-input
                    v-model="
                      contactList.caseErpCustomercontactsList[contactIndex]
                        .f_Post
                    "
                    :placeholder="$t('请输入')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('部门')" labelWidth="60px">
                  <el-input
                    v-model="
                      contactList.caseErpCustomercontactsList[contactIndex]
                        .f_Dep
                    "
                    :placeholder="$t('请输入')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div v-else-if="this.formTitle == '图片查看'" class="erpCase flex_img">
          <l-upload
            :disabled="true"
            style="margin: 16px"
            :limit="2"
            v-model="fileSrc"
            listType="picture-card"
          />
        </div>
        <follow-up-form
          v-else
          ref="followUpForm"
          :isReadOnly="formDetails"
        ></follow-up-form>
      </l-dialog>
    </div>
  </l-layout>
</template>
<script>
const api = window.$api.erpcase.customer;
import FollowUpForm from "./followUpForm";
import OperationRecords from "../material/operationRecords";
import MyForm from "./form";

export default {
  props: {
    isReadOnly: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    FollowUpForm,
    MyForm,
    OperationRecords,
  },
  data() {
    return {
      moduleCode: "erpCase_customerfollow",
      activeName: "tab0",
      fileSrc: "",
      formData: {
        case_erp_customer_f_Name: "", // 客户名称
        case_erp_customer_f_Type: "", // 客户类型
        case_erp_customer_f_Industry: "", // 所在行业
        case_erp_customer_f_Source: "", // 来源
        case_erp_customer_f_Scale: "", // 规模
        case_erp_customer_f_ComNature: "", // 公司性质
        case_erp_customer_f_Address: "", // 地址
        case_erp_customer_f_ModifyUserName: "", // 归属
        case_erp_customer_f_File: "", // 附件
      },
      rules: {},
      // 跟进记录
      // 查询参数
      followQueryData: {},
      followTableLoading: false,
      followTablePageSize: 50,
      followTableTotal: 0,
      followTableCurrentPage: 1,
      case_erp_customerfollow_columns: [
        { label: "跟进方式", prop: "f_Type", align: "left", dataType: "input" },
        {
          label: "跟进时间",
          prop: "f_VisitTime",
          align: "left",
          dataType: "datetime",
          format: "yyyy-MM-dd",
        },
        {
          label: "下次跟进时间",
          prop: "f_NextVisitTime",
          align: "left",
          dataType: "datetime",
          format: "yyyy-MM-dd",
        },
        { label: "说明", prop: "f_Content", align: "left", dataType: "input" },
        {
          label: "跟进人",
          prop: "f_CreateUserName",
          align: "left",
          dataType: "input",
        },
      ],
      case_erp_customerfollow_data: [],

      // 操作记录
      case_erp_log_columns: [
        {
          label: "操作人",
          prop: "f_CreateUserName",
          align: "left",
          dataType: "input",
        },
        {
          label: "操作时间",
          prop: "f_OperateTime",
          align: "left",
          dataType: "input",
        },
        {
          label: "操作",
          prop: "f_Description",
          align: "left",
          dataType: "input",
        },
      ],
      followTableBtns: [
        { prop: "Edit", label: "编辑", width: 100 },
        { prop: "Details", label: "图片查看", disabled: false },
        { prop: "Delete", label: "删除" },
      ],

      // 联系人
      case_erp_customercontacts_columns: [
        {
          id: "case_erp_customercontacts_F_Name",
          prop: "f_Name",
          label: "联系人",
        },
        {
          id: "case_erp_customercontacts_F_Phone",
          prop: "f_Phone",
          label: "电话",
        },
        {
          id: "case_erp_customercontacts_F_Post",
          prop: "f_Post",
          label: "职位",
        },
        { id: "case_erp_customercontacts_F_Dep", prop: "f_Dep", label: "部门" },
        {
          id: "case_erp_customercontacts_F_CreateDate",
          prop: "f_CreateDate",
          dataType: "datetime",
          format: "yyyy-MM-dd",
          label: "创建时间",
        },
        {
          id: "case_erp_customercontacts_F_CreateUserName",
          prop: "f_CreateUserName",
          label: "创建人",
        },
        {
          id: "case_erp_customercontacts_F_IsDefault",
          prop: "f_IsDefault",
          dataType: "mydata",
          label: "是否默认",
          options: [
            { value: 0, label: "是" },
            { value: 1, label: "否" },
          ],
        },
      ],
      case_erp_customercontacts_data: [],
      contactBtn: [
        { prop: "ContactEdit", label: "编辑" },
        { prop: "ContactDelete", label: "删除" },
      ],

      // 操作记录

      // 表单参数
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,
      formDetails: false,

      //
      index: 0,

      // 联系人参数
      contactList: [],
      // 联系人下标数组
      contactIndex: 0,
    };
  },
  computed: {},
  mounted() {
    this.init();
  },

  methods: {
    // 自定义按钮
    filterBtns(row, btns) {
      // console.log("自定义按钮btns",btns)
      // console.log("自定义按钮row",row)
      if (row.f_File == "") {
        btns[1].disabled = true;
        // console.log("btns[2]",btns[2])
      }
      return btns;
    },
    // 联系人 编辑
    async handleContactEdit($index) {
      this.contactList = await this.$awaitWraper(
        api.get(this.formData.case_erp_customer_f_Id)
      );
      // console.log("联系人编辑", data)
      this.contactIndex = $index;

      this.handleShowForm("联系人编辑");
    },
    // 联系人 删除
    async handleContactDelete($index) {
      const data = await this.$awaitWraper(
        api.get(this.formData.case_erp_customer_f_Id)
      );
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(async () => {
          this.case_erp_customercontacts_data.splice($index, 1);
          data.caseErpCustomercontactsList.splice($index, 1);
          await this.$awaitWraper(
            api.update(this.formData.case_erp_customer_f_Id, data)
          );
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除!"),
          });
        });
      // console.log("联系人删除")
    },
    // 编辑
    handleEdit($index, row) {
      this.formEdit = true;
      this.formDetails = false;
      this.formEditRow = row;
      // console.log('编辑', row)
      this.handleShowForm("编辑");
    },
    addFollowUp() {
      this.formEdit = true;
      this.formDetails = false;
      this.handleShowForm("新增用户跟进");
    },
    addContact() {
      this.formEdit = true;
      this.formDetails = false;
      this.handleShowForm("新增联系人");
    },
    // 删除
    handleDelete($index, row) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(async () => {
          this.case_erp_customerfollow_data.splice($index, 1);
          this.followTableTotal--;
          // 删除跟进
          await this.$awaitWraper(api.deleteCustomerfollow(row.f_Id));
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除!"),
          });
        });
    },
    // 详情
    handleDetails($index, row) {
      console.log("详情", $index, row);
      if (row.f_File == "") {
        this.$message({
          type: "info",
          message: this.$t("未上传图片!"),
        });
      } else {
        this.formTitle = "图片查看";
        this.fileSrc = row.f_File;
        this.formVisible = true;
      }
    },
    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");

        if (this.formTitle == "编辑") {
          await this.$refs.followUpForm.loadFormData({
            keyValue: this.formData.case_erp_customer_f_Id,
            customerId: this.formEditRow.f_Id,
          });
        } else if (this.formTitle == "新增联系人") {
          await this.$refs.form.loadFormData({
            keyValue: this.formData.case_erp_customer_f_Id,
          });
        } else if (this.formTitle == "新增用户跟进") {
          await this.$refs.followUpForm.loadFormData({
            keyValue: this.formData.case_erp_customer_f_Id,
          });
        }

        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.followUpForm && this.$refs.followUpForm.resetFormData();
    },

    init() {},
    handleCase_erp_customerfollowAddRow() {
      let point = {};
      point.f_VisitTime = "";
      point.f_NextVisitTime = "";
      point.f_Type = "";
      point.f_Content = "";
      point.f_CreateUserName = "";
      this.case_erp_customerfollow_data.push(point);
    },
    handleCase_erp_customerfollowDeleteRow(event) {
      this.case_erp_customerfollow_data.splice(event.index, 1);
    },
    handleCase_erp_customercontactsAddRow() {
      let point = {};
      point.f_Name = "";
      point.f_Phone = "";
      point.f_Post = "";
      point.f_CreateDate = "";
      point.f_CreateUserName = "";
      point.f_IsDefault = "1";
      this.case_erp_customercontacts_data.push(point);
    },
    handleCase_erp_customercontactsDeleteRow(event) {
      this.case_erp_customercontacts_data.splice(event.index, 1);
    },

    // 重置表单
    resetForm() {
      this.$formClear(this.$refs.form);
      this.activeName = "tab0";
      this.case_erp_customerfollow_data = [];
      this.case_erp_customercontacts_data = [];
    },
    // 校验表单
    async validateForm() {
      if (!(await this.$formValidateWraper(this.$refs.form))) {
        return false;
      }
      if (!this.$refs.case_erp_customerfollow_table.validate()) {
        return false;
      }
      if (!this.$refs.case_erp_customercontacts_table.validate()) {
        return false;
      }

      return true;
    },
    // 设置表单数据
    setForm(data) {
      this.case_erp_customercontacts_data = [];
      this.$setFormData(
        this.formData,
        data.caseErpCustomerEntity,
        "case_erp_customer"
      );
      // this.case_erp_customerfollow_data = data.caseErpCustomerfollowList
      this.case_erp_customercontacts_data = data.caseErpCustomercontactsList;
      if (this.formData.case_erp_customer_f_CreateDate != "") {
        this.formData.case_erp_customer_f_CreateDate =
          this.formData.case_erp_customer_f_CreateDate.split("T")[0];
      }
      this.init();
      // 跟进记录
      this.followLoadTableData();
    },
    // 获取表单数据
    getForm() {
      const formData = {};
      formData.caseErpCustomerEntity = this.$getFormData(
        this.formData,
        "case_erp_customer"
      );
      formData.caseErpCustomerfollowList = this.case_erp_customerfollow_data;
      formData.caseErpCustomercontactsList =
        this.case_erp_customercontacts_data;
      return formData;
    },
    async saveForm({ keyValue, isEdit /*,code,node*/ }) {
      // isEdit 是否更新数据, keyValue 流程中相当于流程processId,code 表示流程中的操作码,node 流程节点
      const postData = this.getForm();
      if (isEdit) {
        // 编辑
        return await this.$awaitWraper(api.update(keyValue, postData));
      } else {
        // 新增
        postData.caseErpCustomerEntity.f_Id = keyValue;

        return await this.$awaitWraper(api.add(postData));
      }
    },

    //  跟进记录数据
    async followLoadTableData() {
      this.followTableLoading = true;
      let queryData = this.$deepClone(this.followQueryData);

      queryData.rows = this.followTablePageSize;
      queryData.page = this.followTableCurrentPage;
      queryData.sidx = "F_Id";
      // console.log('this.formData', this.formData)
      queryData.f_customerId = this.formData.case_erp_customer_f_Id;

      let data = await this.$awaitWraper(api.customerfollows(queryData));

      if (data != null) {
        // console.log("跟进记录数据", data)
        this.case_erp_customerfollow_data = data.rows;
        this.followTableTotal = data.records;
      } else {
        this.case_erp_customerfollow_data = [];
      }
      this.followTableLoading = false;
    },
    async handleSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      if (this.formTitle == "新增联系人") {
        if (await this.$refs.form.validateForm()) {
          const res = await this.$refs.form.saveForm({
            keyValue: this.formEdit ? this.formData.case_erp_customer_f_Id : "",
            isEdit: this.formEdit,
          });
          if (res) {
            const msg = "更新成功!";
            this.$message({
              type: "success",
              message: this.$t(msg),
            });
            const list = await this.$awaitWraper(
              api.get(this.formData.case_erp_customer_f_Id)
            );
            this.setForm(list);
            this.formVisible = false;
          }
        }
      } else if (this.formTitle == "联系人编辑") {
        const res = await this.$awaitWraper(
          api.update(this.formData.case_erp_customer_f_Id, this.contactList)
        );
        if (res) {
          const msg = "更新成功!";
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.formVisible = false;
          this.case_erp_customercontacts_data =
            this.contactList.caseErpCustomercontactsList;
        }
      } else {
        if (this.formTitle == "新增用户跟进") {
          const res = await this.$refs.followUpForm.saveForm({
            keyValue: this.formData.case_erp_customer_f_Id,
          });
          this.$refs.followUpForm.resetForm();
          if (res) {
            const msg = "新增成功!";
            this.$message({
              type: "success",
              message: this.$t(msg),
            });
            this.formVisible = false;
            this.followLoadTableData();
          }
        } else {
          const res = await this.$refs.followUpForm.saveForm({
            keyValue: this.formEdit ? this.formData.case_erp_customer_f_Id : "",
            isEdit: this.formEdit,
          });
          if (res) {
            const msg = this.formEdit ? "更新成功!" : "新增成功!";
            this.$message({
              type: "success",
              message: this.$t(msg),
            });
            this.formVisible = false;
            this.followLoadTableData();
          }
        }
      }
      hideLoading();
    },
  },
};
</script>

<style>
.flex_img .el-upload-list--picture-card {
  display: flex;
}

.lookImg .el-upload-list__item.is-success .el-upload-list__item-status-label {
  display: none !important;
}
</style>
